package net.sf.rose.file.util;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.HeaderFooter;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.HorizontalAlignment;
import com.aspose.words.Paragraph;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.Section;
import com.aspose.words.Shape;
import com.aspose.words.ShapeType;
import com.aspose.words.VerticalAlignment;
import com.aspose.words.WrapType;

import net.sf.rose.jdbc.PageBean;

/** 
 * 类说明：利用Aspose.Cells控件将Word或Excel文件转换成PDF文件
 * @author fengjian E-mail: 9110530@qq.com 
 * @version 创建时间：2018年8月13日
 */
public class PdfUtils {

	static {
		try {
			InputStream is = null;
			is = PdfUtils.class.getResourceAsStream("license.xml");
			com.aspose.cells.License clicense = new com.aspose.cells.License();
			clicense.setLicense(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 功能：把Excel文件转换成PDF文件
	 * @param source - 源Excel文件路径
	 * @param target - 目标PDF文件路径
	 * @return 执行的结果消息
	 */
	public static PageBean excelToPdf(File source, File target) {
		PageBean result = new PageBean();
		try {
			long old = System.currentTimeMillis();
			Workbook wb = new Workbook(new FileInputStream(source));
			wb.save(new FileOutputStream(target), com.aspose.cells.SaveFormat.PDF);
			long now = System.currentTimeMillis();
			result.setMessage("共耗时：" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + target.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
	}

	/**
	 * 功能：把Word文件转换成PDF文件，没有水印
	 * @param source 源Word文件路径
	 * @param target 目标PDF文件路径
	 * @return 执行的结果消息
	 */
	public static PageBean wordToPdf(File source, File target) {
		return wordToPdf(source, target, null);
	}

	/**
	 * 功能：把Word文件转换成PDF文件，有水印
	 * @param source 源Word文件路径
	 * @param target 目标PDF文件路径
	 * @param waterMarkText 水印文字
	 * @return 执行的结果消息
	 */
    public static PageBean wordToPdf(File source, File target, String waterMarkText) {
		PageBean result = new PageBean();
        try {
			long old = System.currentTimeMillis();
			Document doc = new Document(source.getAbsolutePath());
			if (waterMarkText != null) {
				insertWatermarkText(doc, waterMarkText);
			}
            doc.save(new FileOutputStream(target), com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            result.setMessage("共耗时：" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + target.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

	/**
	 * Inserts a watermark into a document.
	 * @param doc The input document.
	 * @param watermarkText Text of the watermark.
	 * 
	 */
	private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
		// Create a watermark shape. This will be a WordArt shape.
		// You are free to try other shape types as watermarks.
		Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
		// Set up the text of the watermark.
		watermark.getTextPath().setText(watermarkText);
		watermark.getTextPath().setFontFamily("Arial");
		watermark.setWidth(500);
		watermark.setHeight(100);
		// Text will be directed from the bottom-left to the top-right corner.
		watermark.setRotation(-40);
		// Remove the following two lines if you need a solid black text.
		watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more
													// Word-style watermark
		watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more
												// Word-style watermark
		// Place the watermark in the page center.
		watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
		watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
		watermark.setWrapType(WrapType.NONE);
		watermark.setVerticalAlignment(VerticalAlignment.CENTER);
		watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
		// Create a new paragraph and append the watermark to this paragraph.
		Paragraph watermarkPara = new Paragraph(doc);
		watermarkPara.appendChild(watermark);
		// Insert the watermark into all headers of each document section.
		for (Section sect : doc.getSections()) {
			// There could be up to three different headers in each section,
			// since we want
			// the watermark to appear on all pages, insert into all headers.
			insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
			insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
			insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
		}
	}

	/**
	 * 插入水印
	 * @param watermarkPara 水印段
	 * @param sect 块
	 * @param headerType 头
	 * @throws Exception 执行异常
	 */
	private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType)
			throws Exception {
		HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
		if (header == null) {
			// There is no header of the specified type in the current section,
			// create it.
			header = new HeaderFooter(sect.getDocument(), headerType);
			sect.getHeadersFooters().add(header);
		}
		// Insert a clone of the watermark into the header.
		header.appendChild(watermarkPara.deepClone(true));
	}

}
